"""
Author: wenbin
Create: 2024-08-22
"""
from flask import current_app, Response
from werkzeug.exceptions import HTTPException

from app.schema import ApiResponse
from .exception import CustomException


def global_exception_handler(e: Exception) -> Response:
    """
    全局异常处理

    :param e: 异常对象
    :return: 响应对象
    """
    app = current_app
    if isinstance(e, CustomException):
        return ApiResponse.fail(code=e.error_code, message=e.message, status_code=e.code)
    elif isinstance(e, HTTPException):
        return ApiResponse.fail(message=e.description, status_code=e.code)
    else:
        if app.config['DEBUG']:
            # 调试模式下打印异常堆栈信息
            raise e
        return ApiResponse.fail(9999, "(っ ̯ -｡) 服务器异常~", 500)
